<script lang="ts" setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import qs from 'qs'
import useClipboard from 'vue-clipboard3'
import { GetDataDetail, PostCreateAccount, PutDetailsRedact } from '@/api/modules/clientAdminAccount.ts'
import detailStore from '@/store/modules/cacheData'
import { GetOptionData as GetStoreOption } from '@/api/modules/store'
import { GetOptionData as GetOpenID } from '@/api/modules/subscriber'

const route = useRoute()
const router = useRouter()
const id = route.query.id as string
const imgDomain = 'https://img1.eprhan.cc'
const detailData = detailStore()

const ruleForm = ref({
  username: '',
  pwd: '',
  mobile: '',
  roleId: 1,
  realname: '',
  nickname: '',
  headimgurl: '',
  expiredTime: '',
  accountState: 1,
  storeId: '',
  openId: '',
  id: 0,
})

const OptionObj = reactive({
  stoerOption: [],
})

const total = ref(0)

// 提交
async function SubmitData() {
  // console.log('提交')
  ruleForm.value.headimgurl = imgDomain + ruleForm.value.headimgurl
  // console.log(ruleForm.value)

  if (id) {
    PutDetailsRedact({ ...ruleForm.value }).then((res: any) => {
      if (res.statusCode === 200) {
        ElMessage.success('修改成功')
        router.push({ name: 'clientAdminAccountIndex' })
      }
      else {
        ElMessage.error(`修改失败。${res.errors}`)
      }
    })
  }
  else {
    PostCreateAccount({ ...ruleForm.value }).then((res: any) => {
      if (res.statusCode === 200) {
        ElMessage.success('添加成功')
        detailData.EmptyDrawactAdminAccount()
        router.push({ name: 'clientAdminAccountIndex' })
      }
      else {
        ElMessage.error(`添加失败。${res.errors}`)
      }
    })
  }
}

// 图片上传赋值
function handleUploadSuccess(url: string) {
  if (url) {
    ruleForm.value.headimgurl = url
  }
}
function extractUrlPart(url: string) {
  return url.replace(/https?:\/\/[^/]+/, '')
}

// 筛选OpenId
const OpenIdOptionList = ref([])

const findFrom = ref({
  UserId: '',
  SCOpenId: '',
  UserPhone: '',
  UserNickName: '',
})
function GetOpenIdOptionList(PageIndex: number = 1, PageSize: number = 20) {
  const params = {
    PageIndex,
    PageSize,
    ...(findFrom.value.UserId && ({ UserIdList: [findFrom.value.UserId] })),
    ...(findFrom.value.SCOpenId && ({ SCOpenId: findFrom.value.SCOpenId })),
    ...(findFrom.value.UserPhone && ({ UserPhone: findFrom.value.UserPhone })),
    ...(findFrom.value.UserNickName && ({ UserNickName: findFrom.value.UserNickName })),
  }
  const parameter = qs.stringify(params)
  GetOpenID(parameter).then((res: any) => {
    if (res.statusCode === 200) {
      OpenIdOptionList.value = res.data.items
      total.value = res.data.total
    }
    else {
      ElMessage.error(`获取数据失败。${res.errors}`)
    }
  })
}

function SetData(OpenId: string) {
  ruleForm.value.openId = OpenId
}

async function copy(OpenId: string) {
  const clipboard = useClipboard()
  try {
    // 使用 navigator.clipboard.writeText 来复制文本
    // await navigator.clipboard.writeText(`pages/adPage/adPage?landing_id=${id}&pushCoupons=0`)
    await clipboard.toClipboard(OpenId)
    ElMessage.success('复制成功')
  }
  catch (error) {
    const textarea = document.createElement('textarea')
    textarea.value = OpenId
    document.body.appendChild(textarea)
    textarea.select()
    // 使用现代浏览器支持的复制命令
    const successful = document.execCommand('copy')
    if (!successful) {
      ElMessage.error('复制失败')
    }
    else {
      ElMessage.success('复制成功')
    }
    document.body.removeChild(textarea)
  }
}

function GetOpenIdData() {
  GetOpenIdOptionList()
}

// 翻页
let PageSize = 20
function handleSizeChange(val: number) {
  GetOpenIdOptionList(1, val)
  PageSize = val
}
function handleCurrentChange(val: number) {
  GetOpenIdOptionList(val, PageSize)
}

watch(ruleForm, (newValue) => {
  detailData.RememberDrawactAdminAccount(newValue)
}, { deep: true })

onMounted(async () => {
  try {
    if (id) {
      GetDataDetail(id).then((res: any) => {
        if (res.statusCode === 200) {
          ruleForm.value = res.data
          ruleForm.value.headimgurl = extractUrlPart(ruleForm.value.headimgurl)
        }
      })
    }
    else {
      ruleForm.value = detailData.GetDrawactAdminAccountData()
    }
    const data2 = await GetStoreOption()
    OptionObj.stoerOption = data2.data

    await GetOpenIdOptionList()
  }
  catch (error) {
    console.error(error)
  }
})
</script>

<template>
  <div>
    <PageHeader :title="id ? '编辑' : '添加'" />
    <ElForm label-position="top" label-width="80px">
      <PageMain title="基础信息">
        <ElRow :gutter="20">
          <ElCol :md="8">
            <ElFormItem label="登录用户名">
              <el-input v-model="ruleForm.username" placeholder="请输入登录用户名" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="登录密码">
              <el-input v-model="ruleForm.pwd" placeholder="请输入登录密码" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="头像">
              <ImageUpload
                :ext="['jpg', 'png']" :size="5" :url="ruleForm.headimgurl" :img-domain="imgDomain"
                @on-success="(imgUrl) => handleUploadSuccess(imgUrl)"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="姓名">
              <el-input v-model="ruleForm.realname" placeholder="请输入姓名" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="昵称（预留）">
              <el-input v-model="ruleForm.nickname" placeholder="请输入昵称" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="手机号">
              <el-input v-model="ruleForm.mobile" placeholder="请输入手机号" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="身份">
              <el-radio-group v-model="ruleForm.roleId">
                <el-radio :value="1" size="large">
                  管理员
                </el-radio>
                <el-radio :value="2" size="large">
                  运营
                </el-radio>
                <el-radio :value="3" size="large">
                  门店
                </el-radio>
              </el-radio-group>
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="状态">
              <el-radio-group v-model="ruleForm.accountState">
                <el-radio :value="1" size="large">
                  正常
                </el-radio>
                <el-radio :value="2" size="large">
                  停用
                </el-radio>
              </el-radio-group>
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="过期时间">
              <el-date-picker
                v-model="ruleForm.expiredTime"
                type="datetime"
                placeholder="请选择日期"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </ElFormItem>
          </ElCol>
          <ElCol v-if="ruleForm.roleId === 3" :md="8">
            <ElFormItem label="门店">
              <el-select v-model="ruleForm.storeId" placeholder="请选择门店" style="width: 300px;">
                <el-option
                  v-for="items in (OptionObj.stoerOption as any)" :key="items.id" :label="`${items.id}-${items.storeName}`" :value="items.id"
                />
              </el-select>
            </ElFormItem>
          </ElCol>
          <ElCol v-if="ruleForm.roleId === 3" :md="8">
            <ElFormItem label="OpenId">
              <el-input v-model="ruleForm.openId" placeholder="请输入用户OpenId" />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </PageMain>
      <PageMain v-if="ruleForm.roleId === 3" title="查询OpenId">
        <ElRow :gutter="20">
          <ElCol :md="5">
            <ElFormItem label="用户ID">
              <el-input v-model="findFrom.UserId" style="width: 300px;" placeholder="请输入用户ID" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="5">
            <ElFormItem label="OpenId">
              <el-input v-model="findFrom.SCOpenId" style="width: 300px;" placeholder="请输入OpenId" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="5">
            <ElFormItem label="微信昵称">
              <el-input v-model="findFrom.UserNickName" style="width: 300px;" placeholder="请输入微信昵称" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="5">
            <ElFormItem label="授权手机号">
              <el-input v-model="findFrom.UserPhone" style="width: 300px;" placeholder="请输入授权手机号" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="4">
            <ElFormItem label="操作">
              <ElButton @click="GetOpenIdData">
                查询
              </ElButton>
            </ElFormItem>
          </ElCol>
          <ElCol :md="24">
            <el-table :data="OpenIdOptionList" stripe style="width: 100%;" border height="400">
              <el-table-column align="center" prop="userId" label="userId" width="150" />
              <el-table-column align="center" prop="scOpenId" label="OpenId" min-width="350" />
              <el-table-column align="center" prop="userNickName" label="微信昵称" width="300" />
              <el-table-column align="center" prop="userPhone" label="核销人手机号" width="200" />
              <el-table-column align="center" prop="address" label="操作" fixed="right" min-width="100">
                <template #default="scope">
                  <ElButton type="primary" @click="SetData(scope.row.scOpenId)">
                    应用
                  </ElButton>
                  <ElButton type="info" style="padding: 0 10px;" @click="copy(scope.row.scOpenId)">
                    复制OpenId
                  </ElButton>
                </template>
              </el-table-column>
            </el-table>
            <div style="height: 10px;" />
            <el-pagination
              :default-page-size="20"
              :page-sizes="[5, 10, 20, 50, 100]"
              layout="total, sizes, ->, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </elcol>
        </elrow>
      </PageMain>
    </ElForm>
    <div style="height: 60px;" />
    <FixedActionBar>
      <ElButton type="primary" size="large" @click="SubmitData">
        提交
      </ElButton>
    </FixedActionBar>
  </div>
</template>

<style scoped>
.from-list {
  position: relative;
  left: 3%;
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  grid-column-gap: 20px;
  width: 95%;
  padding: 20px 30px;
  background-color: white;

  >div {
    min-height: 60px;
  }

  .button {
    padding-top: 20px;
  }
}
</style>
